package cn.manager.travel.dao.impl;

import cn.manager.travel.dao.AdminDao;
import cn.manager.travel.domain.Admin;
import cn.manager.travel.domain.New;
import cn.manager.travel.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Date;
import java.util.List;

public class AdminDaoImpl implements AdminDao {
	private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
	
	@Override
	public List<New> showNews() {
		String sql = "select * from news order by nID desc";
		List<New> news = template.query(sql, new BeanPropertyRowMapper<>(New.class));
		return news;
	}
	
	@Override
	public Admin login(String username, String password) {
		if (username == null || password == null) {
			return null;
		}
		String sql = "select * from admin where username = ? and password = ?";
		Admin admin = null;
		try {
			admin = template.queryForObject(sql, new BeanPropertyRowMapper<>(Admin.class), username, password);
		}catch (Exception e){
//			e.printStackTrace();
		}
		return admin;
	}
	
	@Override
	public void add(String title, String author, String text) {
		if (title == null || author == null || text == null) {
			return;
		}
		String sql = "insert into news values(?,?,?,?,?,?)";
		template.update(sql,null,title,author,0,new Date(),text);
		
	}
	
	@Override
	public void del(Integer nId) {
		if (nId==null){
			return;
		}
		String sql = "delete from news where nId = ?";
		template.update(sql,nId);
	}
	
	@Override
	public void upd(Integer nID, String title, String author, String text) {
		if (title == null || author == null || text == null) {
			return;
		}
		String sql = "update news set title = ? ,author = ?, text = ? where nID = ?";
		template.update(sql,title,author,text,nID);
	}
}
